// web/src/stores/chatStore.ts

import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import type { Conversation, ChatMessage, HistoryItem } from '@/types/chat';

// API 服务（需要根据实际项目调整）
import { 
  getConversationMessages, 
  getConversation, 
  createConversation
} from '@/services/conversation';
import { getHistoryRecords, clearAllHistoryRecords } from '@/services/history';

export const useChatStore = defineStore('chat', () => {
  const router = useRouter();

  // 状态
  const currentConversation = ref<Conversation | null>(null);
  const messages = ref<ChatMessage[]>([]);
  const historyList = ref<HistoryItem[]>([]);
  const isLoading = ref(false);
  const isSending = ref(false);
  const streamError = ref<string | null>(null);
  const hasMoreMessages = ref(true);
  const currentPage = ref(1);
  const messagesPerPage = 20;

  // 计算属性
  const currentConversationId = computed(() => currentConversation.value?.id || null);
  const hasMessages = computed(() => messages.value.length > 0);
  const currentConversationTitle = computed(() => currentConversation.value?.title || '新对话');
  const canLoadMore = computed(() => hasMoreMessages.value && !isLoading.value);
  
  // 最新消息（用于侧边栏显示）
  const latestMessage = computed(() => {
    return messages.value.length > 0 ? messages.value[messages.value.length - 1] : null;
  });

  // 对话统计
  const conversationStats = computed(() => {
    const totalMessages = messages.value.length;
    const userMessages = messages.value.filter(m => m.role === 'user').length;
    const assistantMessages = messages.value.filter(m => m.role === 'assistant').length;
    const toolExecutions = messages.value.reduce((count, msg) => 
      count + (msg.steps?.filter(s => s.type === 'tool_call').length || 0), 0
    );

    return {
      totalMessages,
      userMessages,
      assistantMessages,
      toolExecutions
    };
  });

  // Actions

  /**
   * 设置当前对话
   */
  const setCurrentConversation = (conversation: Conversation | null) => {
    currentConversation.value = conversation;
    // 重置消息相关状态
    messages.value = [];
    currentPage.value = 1;
    hasMoreMessages.value = true;
    streamError.value = null;
  };

  /**
   * 设置消息列表
   */
  const setMessages = (newMessages: ChatMessage[]) => {
    messages.value = newMessages;
  };

  /**
   * 添加消息
   */
  const addMessage = (message: ChatMessage) => {
    messages.value.push(message);
  };

  /**
   * 更新消息
   */
  const updateMessage = (messageId: string | number, updates: Partial<ChatMessage>) => {
    const index = messages.value.findIndex(m => m.id === messageId);
    if (index !== -1) {
      messages.value[index] = { ...messages.value[index], ...updates };
    }
  };

  /**
   * 删除消息
   */
  const deleteMessage = (messageId: string | number) => {
    const index = messages.value.findIndex(m => m.id === messageId);
    if (index !== -1) {
      messages.value.splice(index, 1);
    }
  };

  /**
   * 设置历史记录列表
   */
  const setHistoryList = (history: HistoryItem[]) => {
    historyList.value = history;
  };

  /**
   * 添加历史记录
   */
  const addHistory = (item: HistoryItem) => {
    historyList.value.unshift(item);
  };

  /**
   * 更新历史记录
   */
  const updateHistory = (id: string | number, updates: Partial<HistoryItem>) => {
    const index = historyList.value.findIndex(item => item.id === id);
    if (index !== -1) {
      historyList.value[index] = { ...historyList.value[index], ...updates };
    }
  };

  /**
   * 删除历史记录
   */
  const deleteHistory = (id: string | number) => {
    const index = historyList.value.findIndex(item => item.id === id);
    if (index !== -1) {
      historyList.value.splice(index, 1);
    }
  };

  /**
   * 加载对话
   */
  const loadConversation = async (conversationId: number) => {
    if (isLoading.value) return;

    isLoading.value = true;
    try {
      const conversation = await getConversation(conversationId);
      // 转换status类型，将英文状态转换为中文状态
      const formattedConversation = {
        ...conversation,
        status: (conversation.status === 'in_progress' ? '进行中' : 
                conversation.status === 'completed' ? '已完成' : '失败') as "进行中" | "已完成" | "失败"
      };
      setCurrentConversation(formattedConversation);
      return formattedConversation;
    } catch (error) {
      console.error('Failed to load conversation:', error);
      streamError.value = '加载对话失败';
      throw error;
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 加载对话消息
   */
  const loadConversationMessages = async (conversationId: number, page: number = 1) => {
    if (isLoading.value && page === 1) return;

    isLoading.value = true;
    try {
      // 这里需要根据实际API调整分页参数
      const data = await getConversationMessages(conversationId);
      
      const formattedMessages: ChatMessage[] = data.map((msg: any) => ({
        ...msg,
        steps: msg.meta_data?.steps || msg.steps || []
      }));

      if (page === 1) {
        setMessages(formattedMessages);
      } else {
        messages.value = [...formattedMessages, ...messages.value];
      }

      // 更新分页状态（根据实际API响应调整）
      hasMoreMessages.value = formattedMessages.length === messagesPerPage;
      currentPage.value = page;

      return formattedMessages;
    } catch (error) {
      console.error('Failed to load messages:', error);
      streamError.value = '加载消息失败';
      throw error;
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 加载更多消息（分页）
   */
  const loadMoreMessages = async () => {
    if (!canLoadMore.value || !currentConversationId.value) return;

    const nextPage = currentPage.value + 1;
    await loadConversationMessages(currentConversationId.value, nextPage);
  };

  /**
   * 创建新对话
   */
  const startNewConversation = async (title: string, content: string) => {
    isSending.value = true;
    try {
      const newConv = await createConversation(title, content);
      // 转换status类型，将英文状态转换为中文状态
      const formattedConversation = {
        ...newConv,
        status: (newConv.status === 'in_progress' ? '进行中' : 
                newConv.status === 'completed' ? '已完成' : '失败') as "进行中" | "已完成" | "失败"
      };
      setCurrentConversation(formattedConversation);
      
      // 添加到历史记录
      addHistory({
        id: newConv.id,
        title: newConv.title,
        createdAt: new Date(newConv.created_at),
        status: 'running'
      });

      return formattedConversation;
    } catch (error) {
      console.error('Failed to create conversation:', error);
      streamError.value = '创建对话失败';
      throw error;
    } finally {
      isSending.value = false;
    }
  };

  /**
   * 更新对话标题
   */
  const updateConversationTitle = async (conversationId: number, title: string) => {
    try {
      // 由于updateConversation函数不存在，这里暂时注释掉，实际项目中需要实现这个功能
      // const updated = await updateConversation(conversationId, { title });
      
      if (currentConversation.value?.id === conversationId) {
        currentConversation.value = { ...currentConversation.value, title };
      }

      // 更新历史记录中的标题
      updateHistory(conversationId, { title });

      return currentConversation.value;
    } catch (error) {
      console.error('Failed to update conversation title:', error);
      throw error;
    }
  };

  /**
   * 加载历史记录
   */
  const loadHistory = async () => {
    try {
      const records = await getHistoryRecords();
      const formattedHistory: HistoryItem[] = records.map(record => {
        // 转换status类型，将英文状态转换为中文状态
        const status = record.status === 'pending' ? 'running' : 
                      record.status === 'completed' ? 'completed' : 
                      record.status === 'failed' ? 'failed' : 'interrupted';
        
        return {
          id: record.id,
          title: record.title,
          createdAt: new Date(record.timestamp || Date.now()),
          status: status
        };
      });
      
      setHistoryList(formattedHistory);
      return formattedHistory;
    } catch (error) {
      console.error('Failed to load history:', error);
      // 使用模拟数据作为降级方案
      const fallbackHistory: HistoryItem[] = [
        {
          id: '1',
          title: '登录模块功能测试',
          createdAt: new Date(Date.now() - 3600000),
          status: 'completed'
        },
        {
          id: '2',
          title: '注册模块异常测试',
          createdAt: new Date(Date.now() - 7200000),
          status: 'failed'
        }
      ];
      setHistoryList(fallbackHistory);
      throw error;
    }
  };

  /**
   * 删除历史记录
   */
  const deleteHistoryRecord = async (id: string | number) => {
    try {
      await deleteHistoryRecord(id);
      deleteHistory(id);
    } catch (error) {
      console.error('Failed to delete history record:', error);
      throw error;
    }
  };

  /**
   * 清空所有历史记录
   */
  const clearAllHistory = async () => {
    try {
      await clearAllHistoryRecords();
      setHistoryList([]);
    } catch (error) {
      console.error('Failed to clear history:', error);
      throw error;
    }
  };

  /**
   * 重置状态
   */
  const reset = () => {
    setCurrentConversation(null);
    messages.value = [];
    isLoading.value = false;
    isSending.value = false;
    streamError.value = null;
    hasMoreMessages.value = true;
    currentPage.value = 1;
  };

  /**
   * 切换到新对话
   */
  const switchToNewChat = () => {
    reset();
    router.push({ path: '/chat' });
  };

  /**
   * 切换到历史对话
   */
  const switchToHistory = (conversationId: number) => {
    reset();
    router.push({ 
      path: '/chat',
      query: { conversationId: conversationId.toString() }
    });
  };

  // 监听当前对话变化，自动加载消息
  watch(currentConversationId, (newId) => {
    if (newId) {
      loadConversationMessages(newId);
    }
  }, { immediate: true });

  // 自动加载历史记录
  loadHistory();

  return {
    // 状态
    currentConversation,
    messages,
    historyList,
    isLoading,
    isSending,
    streamError,
    hasMoreMessages,
    currentPage,

    // 计算属性
    currentConversationId,
    hasMessages,
    currentConversationTitle,
    canLoadMore,
    latestMessage,
    conversationStats,

    // Actions
    setCurrentConversation,
    setMessages,
    addMessage,
    updateMessage,
    deleteMessage,
    setHistoryList,
    addHistory,
    updateHistory,
    deleteHistory,
    loadConversation,
    loadConversationMessages,
    loadMoreMessages,
    startNewConversation,
    updateConversationTitle,
    loadHistory,
    deleteHistoryRecord,
    clearAllHistory,
    reset,
    switchToNewChat,
    switchToHistory
  };
});
